extends Sprite2D

@export var dialogue : Resource
@onready var animation_player: AnimationPlayer = %AnimationPlayer
@onready var tip: Sprite2D = %tip
const BALLOON_OFFSET := Vector2(0, -50)   # 气泡相对物体的朝上偏移量
var dialogue_scene
func _input(event: InputEvent) -> void:
	if event.is_action_pressed("interact") and tip.visible == true and dialogue_scene == null:
		get_viewport().set_input_as_handled()
		# 在对话开始时看向玩家
		look_at_player()
		dialogue_scene = DialogueManager.show_dialogue_balloon(dialogue, "start")
		await dialogue_scene.ready
		dialogue_scene.balloon.position = get_global_transform_with_canvas() * BALLOON_OFFSET
		get_tree().paused = true
		
func _on_area_2d_area_entered(_area: Area2D) -> void:
	animation_player.play("!move")

func _on_area_2d_area_exited(_area: Area2D) -> void:
	animation_player.stop()
	tip.visible = false

# 看向玩家的函数
func look_at_player():
	if Utils.player:
		var player_pos = Utils.player.global_position
		var npc_pos = global_position
		# 如果玩家在NPC右边，NPC应该面向右边（flip_h = false）
		# 如果玩家在NPC左边，NPC应该面向左边（flip_h = true）
		flip_h = player_pos.x < npc_pos.x
